package db.ping;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbPing {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length < 3) {
			System.out.printf("Use %s user passwd url%n",DbPing.class.getName());
			return;
		}
		String user = args[0];
		String passwd = args[1];
		String url = args[2];
		boolean success = false; 
		try {
			Connection conn = getConnection(url, user, passwd);
			conn.close();
			success = true;
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.printf("Connect to db %s with user %s %s.%n", url, user, success ? "was successful" : "failed");
	}
	public static Connection getPGConnection(String url, String user, String passwd) throws SQLException, ClassNotFoundException {
		Class.forName("org.postgresql.Driver");
		Connection con = DriverManager.getConnection
		//("jdbc:postgresql://nmssql:5432/pg_utf8", "postgres", "adminpasswd");
		(url, user, passwd);
		return con;
	}
	public static Connection getOracleConnection(String url, String user, String passwd) throws SQLException, ClassNotFoundException {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection con = DriverManager.getConnection( url, user, passwd);
		return con;
	}
	public static Connection getConnection(String url, String user, String passwd) throws SQLException, ClassNotFoundException {
		if (url.toLowerCase().contains("oracle")) {
			return getOracleConnection(url, user, passwd);
		} else if (url.toLowerCase().contains("postgres")) {
			return getPGConnection(url, user, passwd);
		} else {
			throw new IllegalArgumentException("Unknown DB Type:" + url);
		}
	}
}
